package com.xuan.chatroom.service;

import com.xuan.chatroom.mapper.FriendMapper;
import com.xuan.chatroom.model.AddRequest;
import com.xuan.chatroom.model.Friend;
import com.xuan.chatroom.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class FriendService {
    @Autowired
    private FriendMapper friendMapper;

    public List<Friend> queryFriendListByUserID(int userId) {
        return friendMapper.getFriendList(userId);
    }

    public Integer insertAddRequest(AddRequest addRequest) {
        log.info("[insertAddRequest]: " + addRequest);
        // 1.判断数据库是否存在 有效好友申请(即 fromId和toId 都存在且 validFlag == 0)
        // 如果存在且好友申请未被处理（validFlag == 0）则修改申请消息，否则插入申请记录
        if(friendMapper.isExist(addRequest) != null)  {
            addRequest.setValidFlag(0);
            friendMapper.updateAddRequest(addRequest);
            return 0;
        }

        // 2. 检查是否已经为好友了，如果是则不插入好友申请请求(防止已经添加了好友，但那个搜索用户的页面还没关闭，此时可以再次发起添加请求)
        if (friendMapper.isFriend(addRequest) != null) {
            return 0;
        }

        // 3. 不存在有效申请 且 不是好友则插入好友请求
        return friendMapper.insertAddRequest(addRequest);
    }

    public Result getAddRequests(int toId) {
        List<AddRequest> addRecords = friendMapper.getAddRecords(toId);
        if(addRecords.isEmpty()) return Result.success(null);
        return Result.success(addRecords);
    }

    public boolean handle(AddRequest addRequest) {
        log.info("处理好友申请 [handle]: " + addRequest);
        int res = 0;
        // 1. 往数据库的用户关系表中互相添加为好友
        if (addRequest.getValidFlag() == 1) {
            res = mutualAdd(addRequest);
        } else if (addRequest.getValidFlag() == 2) {
         // 2. 拒绝好友申请
            friendMapper.updateAddRequest(addRequest);
        }
        log.info("" + res);
        return res == 2;
    }

    @Transactional
    public Integer mutualAdd(AddRequest addRequest) {
        int res = 0;
        res += friendMapper.addFriend(addRequest.getFromId(), addRequest.getToId());
        res += friendMapper.addFriend(addRequest.getToId(), addRequest.getFromId());
        friendMapper.updateAddRequest(addRequest);
        return res;
    }

}
